package com.Test;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

/**
 * Created by Administrator on 2016/4/20.
 */
@WebFilter(filterName = "ImageFilter")
public class ImageFilter implements Filter {
    private Log log = LogFactory.getLog(this.getClass());  //Log对象
    private String filterName;                             //当前Filter对象
    FilterConfig config;
    public void destroy() {
        filterName = config.getFilterName();
        log.info("销毁Filter: " + filterName+ new Date());
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request   = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse)resp;
        String referer               = request.getHeader("referer"); //链接来源地址
        if(referer == null || !referer.contains(request.getServerName())){
            log.info(referer + request.getServerName());
            request.getRequestDispatcher("/error.png").forward(request,response);
        }else{
            chain.doFilter(request,response);
        }
    }

    public void init(FilterConfig config) throws ServletException {
        filterName = config.getFilterName();
        log.info("启动Filter: " + filterName+ new Date());
    }

}
